package com.situ.stmall.controller;

import java.nio.channels.SeekableByteChannel;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.situ.stmall.entity.User;
import com.situ.stmall.service.UserService;

import ch.qos.logback.core.net.LoginAuthenticator;

@Controller
@RequestMapping("/user")
public class UserController {

	@Autowired
	private UserService userService;
	
	@GetMapping("/reg")
	public String reg() {
		return "/user/reg";
	}
	
	/**
	 * 用户注册
	 */
	@PostMapping("/reg")
	public String reg(User user, String repassword, Model model) {
		//获取参数
		
		//调用service层
		int result = userService.reg(user, repassword);
		
		//返回数据，跳转页面
		if (result > 0) {
			//注册成功
			//跳转到登陆页面
			return "redirect:login";
		}else {
			//登陆失败
			//传递错误信息，
			String error = "未知错误，联系管理人员";
			if (result == -1) {
				error ="账号格式错误";
			}else if (result == -2) {
				error ="密码格式错误";
			}else if (result == -3) {
				error ="两次密码不一致";
			}else if (result == -4) {
				error ="账号不可用";
			}
			model.addAttribute("error", error);
			//跳转注册页面 请求转发
			return "user/reg";
		}
		
	}
	
	/**
	 * 登录页面
	 * 
	 */
	@GetMapping("/login")
	public String login() {
		return "user/login";
	}
	
	/**
	 * 登陆处理页面
	 */
	@PostMapping("/login")
	public String login(User user, Model model, HttpSession session) {
		//获取参数
		//调用
		try {
			user = userService.login(user);
			//保存用户信息到session
			session.setAttribute("user", user);
			
			//跳转主页
			return "redirect:/";
		} catch (Exception e) {
			
			e.printStackTrace();
			//登陆失败
			model.addAttribute("error", e.getMessage());
			return "user/login";
		}
	}
	
	/**
	 * 退出登录
	 */
	@GetMapping("/logout")
	public String logout(HttpSession session) {
		//清除session
		session.invalidate();
		
		//跳转页面
		return "redirect:/";
	}
}
